/*
 * declare_expression.c
 *
 *  Created on: 2013-5-2
 *      Author: xkaying
 */

#include "declare_expression.h"
#include "../common/list.h"
#include "../common/stack.h"

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct _declareexpression{
	//表达式名称
	Token *ptoken;
	//逆波兰表达式
	Stack *ptokenstack;
};

List *pdList=0;

DeclareExpression *DeclareExpressionCreate(Token *ptoken)
{
    //检查列表中的名字
    if(pdList==0){
        pdList=ListInit(0);
    }
    ListCursor *pcursor;
    pcursor=ListGetCursor(pdList);
    DeclareExpression *pnode;
    pnode=(DeclareExpression*)ListForeach(pdList,pcursor);
    while(pnode){
    	if(pnode->ptoken->name==ptoken->name){
    		printf("定义模块错误(.define)：%s命名重复。\n",ptoken->name);
    		return 0;
    	}
    	pnode=(DeclareExpression*)ListForeach(pdList,pcursor);
    }
    //没有发现表示，没有重复名字，导入该定义
    pnode=(DeclareExpression*)malloc(sizeof(DeclareExpression));
    pnode->ptoken=ptoken;
    pnode->ptokenstack=0;
    ListPush(pdList,pnode);
    return pnode;

}

void DeclareExpressionSet(DeclareExpression *pde,Stack *pstack)
{
	assert(pde);
	pde->ptokenstack=pstack;
}

void DeclareExpressionPrint(DeclareExpression *pde)
{
	assert(pde);
	if(pde->ptoken==0){
		printf("错误的declare.ptoken指针为0.\n");
	}
	if(pde->ptoken->type!=TokenType_Variable){
		printf("错误的declare.ptoken.type类型.\n");
	}else{
		printf("标识:%s %d\n",pde->ptoken->name,pde->ptoken->line);
	}

	Token *ptoken;
	StackCursor *pcursor;
	pcursor=StackGetCursor(pde->ptokenstack);
	ptoken=(Token*)StackForeach(pde->ptokenstack,pcursor);

	while(ptoken){
		switch(ptoken->type){
			case TokenType_DeclareOr:{
				printf("\tTokenType_DeclareOr |\n");
				break;
			}
			case TokenType_DeclareMore:{
							printf("\tTokenType_DeclareMore +\n");
							break;
						}
			case TokenType_DeclareLess:{
							printf("\tTokenType_DeclareLess -\n");
							break;
						}
			case TokenType_DeclareBetween:{
							printf("\tTokenType_DeclareBetween ~\n");
							break;
						}
			case TokenType_Variable:{
							printf("\tTokenType_DeclareVariable %s\n",ptoken->name);
							break;
						}
			case TokenType_String:{
							printf("\tTokenType_DeclareString %c\n",ptoken->name[0]);
							break;
						}
			case TokenType_Value:{
							printf("\tTokenType_DeclareValue 0x%s\n",ptoken->name);
							break;
						}
			case TokenType_None:{
				printf("\tTokenType_None\n");
				break;
			}
			default:{
				printf("未知的记号类型.\n");
			}

		}
		ptoken=(Token*)StackForeach(pde->ptokenstack,pcursor);
	}
}
